package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.config.CacheHelper;
import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.utils.DateUtil;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.task.config.MqConst;
import com.atguigu.gmall.task.service.RabbitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author: 李旭
 * @create: 2021-07-28 11:24
 **/
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;
    //查询所有秒杀商品集合
    @GetMapping("/list")
    public List<SeckillGoods> list(){

        return seckillGoodsService.list();
    }
    //去秒杀详情页面
    @GetMapping("/{skuId}.html")
    public SeckillGoods findSeckillGoodsById(@PathVariable Long skuId){
        return seckillGoodsService.findSeckillGoodsById(skuId);
    }
    //查询当前商品的抢购码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        //1:此商品是否为审核通过  不允许抢购
        SeckillGoods seckillGood = seckillGoodsService.findSeckillGoodsById(skuId);
        if(null == seckillGood){
            return Result.fail().message("此商品不存在");
        }
        if(!seckillGood.getStatus().equals("1")){
            return Result.fail().message("此商品不允许售卖");
        }
        //2:此商品是否还有库存  不允许抢购
        if(seckillGood.getStockCount() <= 0){
            return Result.fail().message("此商品已售完");
        }
        //3:此商品是否活动之间  不允许抢购
        //  当前时间>=开始时间    当前时间<开始时间  活动未开始
        //  当前时间<结束时间     当前时间>=结束时间 活动结束了
        if(!DateUtil.dateCompare(seckillGood.getStartTime(),new Date())){
            return Result.fail().message("活动未开始");
        }
        if(DateUtil.dateCompare(seckillGood.getEndTime(),new Date())){
            return Result.fail().message("活动结束了");
        }
        //4:生成抢购码   4.1算法 MD5(userId+skuId)  MD5(自定义的）     4.2 保存缓存
        String userId = AuthContextHolder.getUserId(request);
        String skuIdStr = MD5.encrypt(userId + skuId);
        return Result.ok(skuIdStr);
    }

    //开始秒杀
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,String skuIdStr,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //1、校验抢购码是否正确
        String encrypt = MD5.encrypt(userId + skuId);
        if(!encrypt.equals(skuIdStr)){
            return Result.fail().message("请求非法");
        }
        //2、本地缓存（状态位）
        String state = (String) CacheHelper.get(skuId.toString());
        if(!"1".equals(state)){
            //无货
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
        //3、发消息
        UserRecode userRecode = new UserRecode();
        userRecode.setUserId(userId);
        userRecode.setSkuId(skuId);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                MqConst.ROUTING_SECKILL_USER,userRecode);
        //4
        return Result.ok();
    }
    //轮循查询  每3S执行一次
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
//        1、查询用户是不来过
        Object o = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER + userId + ":"
                + skuId);
        if(null != o){
            //用户来过了
            // 2、查询是否有订单
            Object o1 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
            if(null != o1){
                return Result.build(null,ResultCodeEnum.SECKILL_ORDER_SUCCESS);
            }
//        3、查询是否有抢购资格
            Object o2 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
            if(null != o2){
                return Result.build(null,ResultCodeEnum.SECKILL_SUCCESS);
            }
        }
//        4、查询状态位（败）
        Object state = CacheHelper.get(skuId.toString());
        if(!"1".equals(state)){
            return Result.build(null,ResultCodeEnum.SECKILL_FAIL);
        }
//        5、页面排队中（排）
        return Result.build(null,ResultCodeEnum.SECKILL_RUN);
    }

}
